package site.assad.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;
import site.assad.domain.User;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Author: Al-assad 余林颖
 * E-mail: yulinying_1994@outlook.com
 * Date: 2017/12/15 11:03
 * Description:
 */
@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //验证 user 是否存在
    public boolean checkUserById(final int userid){
        final String sql = "SELECT COUNT(user_id) " +
                "FROM users " +
                "WHERE user_id = ?";
        int result = jdbcTemplate.queryForObject(sql,new Object[]{userid},Integer.class);
        return result > 0;
    }

    //获取 User 相关信息
    public User getUserById(final int userid) {
        final String sql = "SELECT user_id,user_name,user_password,user_icon FROM users WHERE user_id = ? ";

        User user = new User();

        jdbcTemplate.query(sql, new Object[]{userid}, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet rs) throws SQLException {
                user.setId(rs.getInt("user_id"));
                user.setName(rs.getString("user_name"));
                user.setPassword(rs.getString("user_password"));
                user.setIcon(rs.getString("user_icon"));
            }
        });

        return user.getId() == 0 ? null : user;
    }

    public void removeUserById(final int userId){
        final String sql = "DELETE  FROM users WHERE user_id = ? ";
        jdbcTemplate.update(sql,new Object[]{userId});
    }

}
